package com.tjetc._2string;

public class _3StringBuffer {
    public static void main(String[] args) {
        /*
            StringBuffer:
            1. 底层维护了一个可变的byte[] value
            2. StringBuffer 不需要频繁的修改地址 在原位置可以修改 效率高

         */
        StringBuffer stringBuffer = new StringBuffer();

        // 相互转换
        String a = "zhangsan";
        StringBuffer stringBuffer1 = new StringBuffer(a);
        System.out.println(stringBuffer1);

        String b = stringBuffer1.toString(); // toString底层实际上new了
        System.out.println(b);

        System.out.println(a == b); // false


        // 特殊情况
        String c = null;
        /*
            AbstractStringBuilder(String str) {
                int length = str.length(); // 这里会报空指针异常
                int capacity = (length < Integer.MAX_VALUE - 16)
                        ? length + 16 : Integer.MAX_VALUE;
                final byte initCoder = str.coder();
                coder = initCoder;
                value = (initCoder == LATIN1)
                        ? new byte[capacity] : StringUTF16.newBytesFor(capacity);
                append(str);
            }


         */
//        StringBuffer stringBuffer2 = new StringBuffer(c);

        // 可以存null
        StringBuffer stringBuffer3 = new StringBuffer();
        /*
            private AbstractStringBuilder appendNull() {
                ensureCapacityInternal(count + 4);
                int count = this.count;
                byte[] val = this.value;
                if (isLatin1()) {
                    val[count++] = 'n';
                    val[count++] = 'u';
                    val[count++] = 'l';
                    val[count++] = 'l';
                } else {
                    count = StringUTF16.putCharsAt(val, count, 'n', 'u', 'l', 'l');
                }
                this.count = count;
                return this;
            }

         */
        stringBuffer3.append(c);
        stringBuffer3.append("abc");
        System.out.println(stringBuffer3);
        System.out.println(stringBuffer3.length()); // 4
    }
}
